package com.kingmed.kmss.framework.feign.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.kingmed.kmss.common.constant.sys.UserConstants;
import com.kingmed.kmss.common.dto.admin.ums.LoginUserAuthDTO;
import com.kingmed.kmss.common.dto.admin.ums.LoginUserDTO;
import com.kingmed.kmss.common.dto.admin.ums.OrganizationTileDTO;
import com.kingmed.kmss.common.dto.admin.ums.RoleDTO;
import com.kingmed.kmss.common.enums.admin.OrgLevel;
import com.kingmed.kmss.common.exception.BusinessException;
import com.kingmed.kmss.common.satoken.LoginHelper;
import com.kingmed.kmss.framework.feign.client.admin.CommonAdminFeignServiceFacade;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class LoginUserUtil {

    private static CommonAdminFeignServiceFacade commonAdminFeignServiceFacade;

    @Autowired
    private void setCommonAdminFeignServiceFacade(CommonAdminFeignServiceFacade commonAdminFeignServiceFacade){
        this.commonAdminFeignServiceFacade = commonAdminFeignServiceFacade;
    }

    /**
     * 获取用户-封装userId为空情况(如果非登录状态下调用，直接抛异常)
     */
    public static LoginUserDTO getLoginUser() {
        LoginUserDTO loginUser = LoginHelper.getLoginUser();
        if(loginUser.getUserId() == null || loginUser.getUserId() == 0){
            throw new BusinessException("未登陆无权限操作，请先登录");
        }
       return loginUser;
    }

    /**
     * 获取用户ID
     */
    public static Long getLoginUserId() {
        LoginUserDTO loginUser = getLoginUser();
        return loginUser.getUserId();
    }

    /**
     * 获取用户名称
     */
    public static String getLoginUserName() {
        LoginUserDTO loginUser = getLoginUser();
        return loginUser.getUsername();
    }

    public static LoginUserAuthDTO getLoginUserAuth() {
        return getLoginUserAuth(null);
    }

    /**
     * 获取用户名称
     */
    public static LoginUserAuthDTO getLoginUserAuth(LoginUserDTO loginUser) {
        if(loginUser == null || loginUser.getUserId() == null || loginUser.getUserId() == 0) {
            loginUser = getLoginUser();
        }
        LoginUserAuthDTO loginUserAuth = new LoginUserAuthDTO();
        BeanUtil.copyProperties(loginUser,loginUserAuth);
        if(UserConstants.ADMIN_ID.equals(loginUser.getUserId())){
            loginUserAuth.setAuthType(OrgLevel.GROUP.getCode().toString());
            return loginUserAuth;
        }
        if(CollectionUtils.isEmpty(loginUser.getRoles())){
            loginUserAuth.setAuthType("99");
            return loginUserAuth;
        }

        if(StrUtil.isBlank(loginUserAuth.getAuthType()) && CollectionUtils.isNotEmpty(loginUser.getOrgs())){
            //分配的角色中，是否存在集团
            List<RoleDTO> roleList = loginUser.getRoles().stream()
                    .filter(t->OrgLevel.GROUP.getCode().toString().equals(t.getDataScope())).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(roleList)){
                loginUserAuth.setAuthType(OrgLevel.GROUP.getCode().toString());
                return loginUserAuth;
            }

            //分配的角色中，是否存在大区,有大区，取大区
            roleList = loginUser.getRoles().stream()
                    .filter(t->OrgLevel.REGION.getCode().toString().equals(t.getDataScope())).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(roleList)) {
                loginUserAuth.getRegionList().clear();
                loginUserAuth.setAuthType(OrgLevel.REGION.getCode().toString());
                OrganizationTileDTO umsOrganizationTileDTO = commonAdminFeignServiceFacade.getGroupRegionBranchByAdminId(loginUser.getUserId());
                if (ObjectUtil.isNotNull(umsOrganizationTileDTO)) {
                    loginUserAuth.getRegionList().add(umsOrganizationTileDTO.getRegionId());
                }
            }else {
                //分配的角色中，是否存在子公司,有子公司，取子公司
                roleList = loginUser.getRoles().stream()
                        .filter(t -> OrgLevel.BRANCH.getCode().toString().equals(t.getDataScope())).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(roleList)) {
                    loginUserAuth.getCompanyList().clear();
                    loginUserAuth.setAuthType(OrgLevel.BRANCH.getCode().toString());
                    OrganizationTileDTO umsOrganizationTileDTO = commonAdminFeignServiceFacade.getGroupRegionBranchByAdminId(loginUser.getUserId());
                    if (ObjectUtil.isNotNull(umsOrganizationTileDTO)) {
                        loginUserAuth.getCompanyList().add(umsOrganizationTileDTO.getSubCompanyId());
                    }
                }else{
                    loginUserAuth.setAuthType("99");
                }
            }
        }

        return loginUserAuth;
    }

    public static LoginUserAuthDTO getLoginUserAuthComm(LoginUserDTO loginUser) {
        if(loginUser == null || loginUser.getUserId() == null || loginUser.getUserId() == 0) {
            loginUser = getLoginUser();
        }
        LoginUserAuthDTO loginUserAuth = new LoginUserAuthDTO();
        BeanUtil.copyProperties(loginUser,loginUserAuth);
        if(UserConstants.ADMIN_ID.equals(loginUser.getUserId())){
            loginUserAuth.setAuthType(OrgLevel.GROUP.getCode().toString());
            return loginUserAuth;
        }
        if(CollectionUtils.isEmpty(loginUser.getRoles())){
            loginUserAuth.setAuthType("99");
            return loginUserAuth;
        }

        if(StrUtil.isBlank(loginUserAuth.getAuthType()) && CollectionUtils.isNotEmpty(loginUser.getOrgs())){
            //分配的角色中，是否存在集团
            List<RoleDTO> roleList = loginUser.getRoles().stream()
                    .filter(t->OrgLevel.GROUP.getCode().toString().equals(t.getDataScope())).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(roleList)){
                loginUserAuth.setAuthType(OrgLevel.GROUP.getCode().toString());
                return loginUserAuth;
            }

            //分配的角色中，是否存在大区,有大区，取大区
            roleList = loginUser.getRoles().stream()
                    .filter(t->OrgLevel.REGION.getCode().toString().equals(t.getDataScope())).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(roleList)) {
                loginUserAuth.setAuthType(OrgLevel.REGION.getCode().toString());
            }else {
                //分配的角色中，是否存在子公司,有子公司，取子公司
                roleList = loginUser.getRoles().stream()
                        .filter(t -> OrgLevel.BRANCH.getCode().toString().equals(t.getDataScope())).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(roleList)) {
                    loginUserAuth.setAuthType(OrgLevel.BRANCH.getCode().toString());
                }else{
                    loginUserAuth.setAuthType("99");
                }
            }
        }

        return loginUserAuth;
    }

    /**
     * 数据权限范围-用于对外接口
     */
    public static LoginUserAuthDTO getLoginUserAuthForOpen(LoginUserDTO loginUser) {
        if(loginUser == null || loginUser.getUserId() == null || loginUser.getUserId() == 0) {
            LoginUserAuthDTO loginUserAuth = new LoginUserAuthDTO();
            loginUserAuth.setAuthType(OrgLevel.GROUP.getCode().toString());
            return loginUserAuth;
        }
        return getLoginUserAuth(loginUser);
    }


}
